package com.zzh.custom.dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Point;
import android.text.TextUtils;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.ColorRes;
import androidx.annotation.NonNull;


import com.zzh.custom.LevelSelectView;
import com.zzh.custom.R;

import java.util.List;

/**
 * @author zhangzhihao
 * @email zhangzhihao@gongjiangren.net
 * @date 2020-10-13
 * @desc 多层级选择器
 */
public class LevelSelectDialog extends Dialog {

    public interface OnLevelSelectListener {
        void onResults(List<? extends LevelSelectView.SelectMoudle> mDatas, List<Integer> indexs);
    }

    public interface OnLevelMultiSelectListener {
        void onResults(List<? extends LevelSelectView.SelectMoudle> mDatas, List<List<Integer>> indexs);
    }

    private LevelSelectView levelSelectView;
    private TextView titleView;
    private Button confirmView;
    private OnLevelSelectListener mOnLevelSelectListener;
    private OnLevelMultiSelectListener mOnLevelMultiSelectListener;

    private LevelSelectDialog(@NonNull Context context) {
        this(context, R.style.custom_level_select_dialog);
    }

    private LevelSelectDialog(@NonNull Context context, int themeResId) {
        super(context, themeResId);
        setContentView(R.layout.custom_dialog_level_select);
        levelSelectView = findViewById(R.id.levelSelectView);
        titleView = findViewById(R.id.dialogTitle);
        levelSelectView.setOnSelectListener(new LevelSelectView.OnSelectListener() {
            @Override
            public void onResults(List<? extends LevelSelectView.SelectMoudle> datas, List<Integer> indexs) {
                dismiss();
                if (mOnLevelSelectListener != null) {
                    mOnLevelSelectListener.onResults(datas, indexs);
                }
            }

            @Override
            public void onMultiCount(int count) {
                if (count == 0) {
                    confirmView.setClickable(false);
                    confirmView.setEnabled(false);
                    confirmView.setText("确认");
                } else {
                    confirmView.setClickable(true);
                    confirmView.setEnabled(true);
                    confirmView.setText(String.format("确认（已选%s个）", count));
                }
            }
        });

        Window dialogWindow = getWindow();
        if (dialogWindow != null) {
            dialogWindow.setWindowAnimations(R.style.level_select_slide_anim);
            dialogWindow.setGravity(Gravity.RIGHT);
            WindowManager.LayoutParams p = dialogWindow.getAttributes();
            WindowManager m = dialogWindow.getWindowManager();
            dialogWindow.getDecorView().setPadding(0, 0, 0, 0);
            Display d = m.getDefaultDisplay();
            Point point = new Point();
            d.getSize(point);
            p.height = WindowManager.LayoutParams.MATCH_PARENT;
            p.width = (int) (point.x * 0.76);
            dialogWindow.setAttributes(p);
        }
        setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                if (levelSelectView != null) {
                    levelSelectView.onClearAnimator();
                }
            }
        });

    }

    /**
     * 创建dialog入口
     *
     * @param context    上下文
     * @param themeResId 样式id -1为默认样式
     * @return 当前对象
     */
    private static LevelSelectDialog newInstance(Context context, int themeResId) {
        if (themeResId != -1) {
            return new LevelSelectDialog(context, themeResId);
        }
        return new LevelSelectDialog(context);
    }


    private LevelSelectDialog setDatas(List<? extends LevelSelectView.SelectMoudle> datas, int count, int defaultCount,
                                       @ColorRes int[] bg,
                                       @ColorRes int[] itemBg,
                                       @ColorRes int[] selectBg,
                                       @ColorRes int[] textDefault,
                                       @ColorRes int[] textSelect) {
        levelSelectView.setDatas(datas, count, defaultCount, bg, itemBg, selectBg, textDefault, textSelect);
        return this;
    }


    private LevelSelectDialog setOnLevelSelectListener(OnLevelSelectListener onLevelSelectListener) {
        this.mOnLevelSelectListener = onLevelSelectListener;
        return this;
    }

    private LevelSelectDialog setOnLevelMultiSelectListener(OnLevelMultiSelectListener onLevelMultiSelectListener) {
        this.mOnLevelMultiSelectListener = onLevelMultiSelectListener;
        return this;
    }

    private LevelSelectDialog setMyTitle(String title) {
        if (TextUtils.isEmpty(title)) {
            return this;
        }
        titleView.setVisibility(View.VISIBLE);
        findViewById(R.id.line).setVisibility(View.VISIBLE);
        titleView.setText(title);
        return this;
    }

    private LevelSelectDialog setShowBack(boolean isShowBack, int backDrawId) {
        if (isShowBack) {
            if (backDrawId <= 0) {
                findViewById(R.id.back).setVisibility(View.GONE);
                return this;
            }
            ImageView view = findViewById(R.id.back);
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();
                }
            });
            view.setVisibility(View.VISIBLE);
            view.setImageResource(backDrawId);
        } else {
            findViewById(R.id.back).setVisibility(View.GONE);
        }
        return this;
    }

    private LevelSelectDialog setShowHearder(boolean showHearder) {
        findViewById(R.id.headerLl).setVisibility(showHearder ? View.VISIBLE : View.GONE);
//        findViewById(R.id.confirm).setVisibility(View.VISIBLE);
        return this;
    }

    /**
     * 设置为多选
     *
     * @param maxSelectCount 最多选多少个
     * @return
     */
    private LevelSelectDialog setMultiSelect(int maxSelectCount, List<List<Integer>> selectIndex, List<Integer> allowMultiSelects) {
        confirmView = findViewById(R.id.confirm);
        confirmView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
                if (mOnLevelMultiSelectListener != null) {
                    mOnLevelMultiSelectListener.onResults(levelSelectView.getDatas(), levelSelectView.getMultiSelectIndexs());
                }
            }
        });

        confirmView.setVisibility(View.VISIBLE);
        if (selectIndex != null && selectIndex.size() > 0) {
            confirmView.setClickable(true);
            confirmView.setText(String.format("保存（已选%s个）", selectIndex.size()));
        } else {
            confirmView.setClickable(false);
        }
        levelSelectView.setMultiSelect(maxSelectCount, selectIndex, allowMultiSelects);
        return this;
    }

    private LevelSelectDialog setSingleSelect(List<Integer> singleSelect) {
        levelSelectView.setSingleSelect(singleSelect);
        return this;
    }


    public static class Builder {

        /**
         * 单列背景色
         */
        private @ColorRes
        int[] bg;
        /**
         * 单个item默认背景色
         */
        private @ColorRes
        int[] itemBg;
        /**
         * 单个item选中背景色
         */
        private @ColorRes
        int[] selectBg;
        /**
         * 字体默认色
         */
        private @ColorRes
        int[] textDefault;
        /**
         * 字体选中色
         */
        private @ColorRes
        int[] textSelect;

        /**
         * 数据源
         */
        private List<? extends LevelSelectView.SelectMoudle> datas;

        // 单选监听
        private OnLevelSelectListener onLevelSelectListener;
        // 多选确定监听
        private OnLevelMultiSelectListener onLevelMultiSelectListener;
        /**
         * 共多少层级
         */
        private int count = 3;

        /**
         * 默认展示列数
         * 当有记录时无效
         */
        private int defaultCount = 0;

        /**
         * 显示的title
         */
        private String title;

        /**
         * 多选 最多选多少个 （单选无用）
         */
        private int maxSelectCount = 5;
        /**
         * 是不是多选
         */
        private boolean isMultiSelect = false;
        /**
         * 多选模式
         * 1-> 所有列都可以多选
         * 2 -> 指定列可以多选
         * 其他参数 均视为不合法
         */
        private int multiSelectMolde = 1;
        /**
         * 指定多选的列
         * multiSelectMolde == 2 有效
         */
        private List<Integer> allowMultiSelects;
        /**
         * 多选 选中的数据 （单选无用）
         */
        private List<List<Integer>> multiSelects;

        /**
         * 单选选中的数据
         */
        private List<Integer> singleSelect;

        /**
         * 是不是显示back
         * true false
         */
        private boolean isShowBack;
        private int backDrawId = -1;

        private boolean isShowHearder = true;

        public Builder setShowHearder(boolean showHearder) {
            this.isShowHearder = showHearder;
            return this;
        }

        public Builder setShowBack(boolean showBack, int backDrawId) {
            this.isShowBack = showBack;
            this.backDrawId = backDrawId;
            return this;
        }

        public Builder setDatas(List<? extends LevelSelectView.SelectMoudle> datas) {
            this.datas = restoreDatas(datas);
            return this;
        }

        public Builder setMultiSelectMolde(int multiSelectMolde, List<Integer> allowMultiSelects) {
            this.isMultiSelect = true;
            this.allowMultiSelects = allowMultiSelects;
            this.multiSelectMolde = multiSelectMolde;
            return this;
        }

        private List<? extends LevelSelectView.SelectMoudle> restoreDatas(List<? extends LevelSelectView.SelectMoudle> datas) {
            if (datas == null || datas.size() <= 0) {
                return null;
            }
            for (int i = 0; i < datas.size(); i++) {
                datas.get(i).setSelect(false);
                restoreDatas(datas.get(i).getChildSelectMoudles());
            }
            return datas;
        }

        public Builder setOnLevelMultiSelectListener(OnLevelMultiSelectListener onLevelMultiSelectListener) {
            this.onLevelMultiSelectListener = onLevelMultiSelectListener;
            return this;
        }

        public Builder setOnLevelSelectListener(OnLevelSelectListener onLevelSelectListener) {
            this.onLevelSelectListener = onLevelSelectListener;
            return this;
        }

        public Builder setCount(int count) {
            this.count = count;
            return this;
        }

        public Builder setMaxSelectCount(int maxSelectCount) {
            this.maxSelectCount = maxSelectCount;
            return this;
        }

        public Builder setSingleSelect(List<Integer> singleSelect) {
            this.singleSelect = singleSelect;
            return this;
        }

        public Builder setMultiSelect(boolean multiSelect) {
            isMultiSelect = multiSelect;
            return this;
        }

        public Builder setMultiSelects(List<List<Integer>> multiSelects) {
            this.multiSelects = multiSelects;
            return this;
        }

//        public Builder setDefaultCount(int defaultCount) {
//            this.defaultCount = defaultCount;
//            return this;
//        }


        public Builder setColors(@ColorRes int[] bg,
                                 @ColorRes int[] itemBg,
                                 @ColorRes int[] selectBg,
                                 @ColorRes int[] textDefault,
                                 @ColorRes int[] textSelect) {
            this.bg = bg;
            this.itemBg = itemBg;
            this.selectBg = selectBg;
            this.textDefault = textDefault;
            this.textSelect = textSelect;
            return this;
        }

        public Builder setTitle(String title) {
            this.title = title;
            return this;
        }

        private int[] generateColors(int count, int... color) {
            int[] colors = new int[count];
            for (int i = 0; i < colors.length; i++) {
                colors[i] = color.length > i ? color[i] : color[color.length - 1];
            }
            return colors;
        }

        public LevelSelectDialog builder(Context context) {
            bg = bg == null ? generateColors(count, R.color.color_ffffff, R.color.color_f8f8f8, R.color.color_f2f3f4) : bg;
            selectBg = selectBg == null ? generateColors(count, R.color.color_f8f8f8, R.color.color_f2f3f4, R.color.color_eaeaea) : selectBg;
            textDefault = textDefault == null ? generateColors(count, R.color.color_333333, R.color.color_333333, R.color.color_333333) : textDefault;
            textSelect = textSelect == null ? generateColors(count, R.color.color_0a7efc, R.color.color_0a7efc, R.color.color_0a7efc) : textSelect;
            LevelSelectDialog levelSelectDialog = LevelSelectDialog
                    .newInstance(context, -1);

            if (isMultiSelect) {
                if (multiSelectMolde == 1) {
                    levelSelectDialog
                            .setMultiSelect(maxSelectCount, multiSelects, null)
                            .setOnLevelMultiSelectListener(onLevelMultiSelectListener);
                } else if (multiSelectMolde == 2) {
                    if (allowMultiSelects == null || allowMultiSelects.size() <= 0) {
                        throw new IllegalArgumentException("选择的模式不符合要求");
                    }
                    levelSelectDialog
                            .setMultiSelect(maxSelectCount, multiSelects, allowMultiSelects)
                            .setOnLevelMultiSelectListener(onLevelMultiSelectListener);
                } else {
                    throw new IllegalArgumentException("选择的模式不符合要求");
                }
            } else {
                levelSelectDialog
                        .setSingleSelect(singleSelect)
                        .setOnLevelSelectListener(onLevelSelectListener);
            }

            levelSelectDialog
                    .setShowHearder(isShowHearder)
                    .setMyTitle(title)
                    .setShowBack(isShowBack, backDrawId)
                    .setDatas(datas, count, defaultCount, bg, itemBg, selectBg, textDefault, textSelect);

            return levelSelectDialog;
        }
    }

}
